<?php

namespace App\Http\Services;

use App\Http\Model\Room;
use App\Http\Model\RoomManualManagement;
use App\Http\Model\System;
use App\Http\Model\UserRegisterLog;
use Illuminate\Support\Facades\Schema;

/**
 * 房间手动推荐池
 */
class RoomManualManagementServices extends CommonServices
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取多少个手动推荐池配置的房间, 默认5个，可以通过系统设置功能改动
     *
     * @return int
     */
    public function getManualManagementRoomNumber(): int
    {
        $key = 'room_manual_management_number';//系统配置的key
        $configs = (new System())->get_config();
        return intval($configs[$key]['value'] ?? 5);
    }

    /**
     * 获取手动推荐房间id
     *
     * @param int $userId
     * @return array
     */
    public function getManualManagementRoomIds(int $userId): array
    {
        $ids = [];
        //查询用户的渠道
        $platform = UserRegisterLog::query()->select(['platform'])->where('user_id', $userId)->first();
        if (!$platform) {
            return $ids;
        }

        //判断表结构是否存在，防止上线时，还未执行数据迁移而报错
        $model = new RoomManualManagement();
        if (!Schema::hasTable($model->getTable())) {
            return $ids;
        }


        $platform = $platform->platform;
        $randRoomUuids = $this->getRandomRoomUuidsByPlatform(strval($platform));
        return $this->getOpenedRoomIds($randRoomUuids);
    }

    /**
     * 根据渠道随机获取room_uid,默认返回5个
     *
     * @param string $platform
     * @return array
     */
    private function getRandomRoomUuidsByPlatform(string $platform): array
    {
        $defaultPlatformKey = '默认';
        $randRoomUuids = [];
        $model = new RoomManualManagement();
        $allRoomUuids = $model->getALlRoomUIdsFromCache($platform);
        if (!$allRoomUuids) {
            $platform = $defaultPlatformKey;
            $allRoomUuids = $model->getALlRoomUIdsFromCache($platform);
        }

        if ($allRoomUuids) {
            shuffle($allRoomUuids);//打乱顺序
            $number = $this->getManualManagementRoomNumber();
            if (count($allRoomUuids) > $number) {//取number个
                $randRoomUuids = array_slice($allRoomUuids, 0, $number);
            } else {
                $randRoomUuids = $allRoomUuids;
            }
        }

        return $randRoomUuids;
    }

    /**
     * 过滤掉未开启的房间
     *
     * @param array $randRoomUuids
     * @return array
     */
    private function getOpenedRoomIds(array $randRoomUuids): array
    {
        $newRoomIds = [];
        $roomIds = Room::query()->select(['room_id'])->whereIn('room_uid', $randRoomUuids)->pluck('room_id')->toArray();
        if (!$roomIds) {
            return $newRoomIds;
        }

        $roomModel = new Room();
        foreach ($roomIds as $id) {
            $openStatus = $roomModel->get_opened($id);
            if ($openStatus) {//未开启，删掉
                $newRoomIds[] = $id;
            }
        }

        return $newRoomIds;
    }

    /**
     * 根据用户id获取推荐的房间ids
     * @author  zxiaofee
     * @param int $userId
     * @return array
     */
    public function getRoomIdsByUid(int $userId): array
    {
        $plateform = $this->getPlatefromByUid($userId);
        $allRoomIds = $this->getAllRoomIdsByPlatform($plateform);
        $num = $this->getManualManagementRoomNumber();
        shuffle($allRoomIds);
        if (count($allRoomIds) > $num) {//取number个
            $randRoomIds = array_slice($allRoomIds, 0, $num);
        } else {
            $randRoomIds = $allRoomIds;
        }
        
        return $randRoomIds;
    }


    /**
     * 根据用户id获取plateform 这个plateform呢类似抖音 微信等引流渠道吧
     * @author  zxiaofee
     * @param int $userId
     * @return string
     */
    public function getPlatefromByUid(int $userId): string
    {
        $platform =  UserRegisterLog::query()->select(['platform'])->where('user_id', $userId)->first();
        if(!$platform){
            return '';
        }
        $platform = $platform->platform;

        return strval($platform);
    }

    /**
     * 根据渠道随机获取所有房间id
     * @author  zxiaofee
     * @param string $platform
     * @return array
     */
    private function getAllRoomIdsByPlatform(string $plateform): array
    {
        //如果plateform为空则赋值默认 贼不落空
        $plateform  = $plateform==''?'默认': $plateform;

        //判断表结构是否存在，防止上线时，还未执行数据迁移而报错
        $model = new RoomManualManagement();
        $allRoomIds = $model->getAllRoomIdsByPlatefromFromCache($plateform);
        if($allRoomIds !== null){
            return $allRoomIds;
        }

        if (!Schema::hasTable($model->getTable())) {
            return [];
        }

        $defaultPlatformKey = '默认';
        $model = new RoomManualManagement();
        $allRoomUuids = $model->getALlRoomUIdsFromCache($plateform);
        if (!$allRoomUuids) {
            $platform = $defaultPlatformKey;
            $allRoomUuids = $model->getALlRoomUIdsFromCache($plateform);
        }

        $allRoomIds = $this->getOpenedRoomIds($allRoomUuids);

        $model->setAllRoomIdsByPlatefromToCache($plateform, $allRoomIds);

        return $allRoomIds;
    }
}